//
//  BKOrderDeliveryDateViewController.m
//  bestkeep
//
//  Created by 马乾征 on 16/11/24.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKOrderDeliveryDateViewController.h"
#import "BK_OD_Color.h"
#import "BK_Confirm_Order_Common.h"
#import <EventKit/EventKit.h>
#import "UIView+BKOrderMenu.h"
#import <FSCalendarCell.h>
#import <IQKeyboardManager.h>
#import "Mediator+BKSC.h"
#import "Mediator+BKMy.h"
#import "BKODCalendarView.h"
#import "BK_Calendar_Tool.h"

#import "BK_OD_Price_Cell.h"
#import "BK_OD_Count_Cell.h"
#import "BK_OD_MatchNum_Cell.h"

#import "BK_OD_Prompt_Msg.h"
#import "BK_OD_Footer_View.h"
#import "BK_OD_LimitBuy_View.h"
#import "BK_OD_Footer_PromptMsg.h"

@interface BKODSendObject : NSObject
@property(nonatomic, strong)NSString *amount;
@property(nonatomic, strong)NSString *sendDate;
@property(nonatomic, strong)NSString *price;
@property(nonatomic, strong)NSString *thbuyflag;
@end
@implementation BKODSendObject
@end

@interface BKOrderDeliveryDateViewController ()
<
    UITableViewDelegate,
    UITableViewDataSource,
    UIGestureRecognizerDelegate,
    BKODSelectPriceCellDelegate,
    BKODSelectCountCellDelegate,
    BKODFooterPromptMsgDelegate,
    BKODBFooterViewDelegate,
    BKODCalendarViewDelegate,
    WLDecimalKeyboardDelegate
>
@property(nonatomic, strong)UITableView *tabV_calendar;
@property(nonatomic, strong)BKODCalendarView *view_calendar;//日历
@property(nonatomic, strong)BK_OD_Footer_View *view_ODBfooter;//加入购物车与立即付款
@property(nonatomic, strong)UIButton *btn_lastMonth;//左边翻页按钮
@property(nonatomic, strong)UIButton *btn_nextMonth;//右边翻页按钮
@property(nonatomic, strong)ExceptionView *exceptionView;

@property(nonatomic, strong)NSCalendar *ODCalendar;
@property(nonatomic, strong)NSDateFormatter *formatter_date;//日期格式
@property(nonatomic, strong)NSArray <EKEvent *> *arr_events;//用来存放节气
@property(nonatomic, strong)NSMutableArray <NSArray <BKODDeliveryDate *> *> *marr_deliveryDate;//存放日历数据的数组
@property(nonatomic, strong)NSArray <SectionModel *> *arr_section;

@property(nonatomic, strong)BKODSendObject *send_Obj; //给下级界面传参使用
@property(nonatomic, assign)BOOL isKeyboardIsVisible;//键盘是否出现
@property(nonatomic, assign)NSInteger matchNum_Index;
@property(nonatomic, assign)NSInteger countIndex;
@property(nonatomic, assign)double price_Difference;// 此字段专门用来给后台传递出价的价格初始值   【含糖赋-不含】




/*
 * 当前使用的月份
 */
@property(nonatomic, strong) NSString * str_Use_Month;

@property(nonatomic, strong) NSString * str_mini_Month;//最小月份
@property(nonatomic, strong) NSString * str_max_Month; //最大月份
@property(nonatomic, strong) NSDate *mini_mumDate;//日历数据范围的最小月份
@property(nonatomic, strong) NSDate *maxi_mumDate;//日历数据范围的最大月份

@property(nonatomic, strong) NSMutableDictionary * mdic_deliveryDate;



@end

@implementation BKOrderDeliveryDateViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setProperty];
    [self createUI];
    [self check_NetWork];
    [self BK_add_KeyboardNotifications];//键盘通知
    [[IQKeyboardManager sharedManager] disableDistanceHandlingInViewControllerClass:[self class]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    kOrderDismiss;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (_view_ODBfooter) {
        [_view_ODBfooter updateShoppingCartAmount];
    }
}

#pragma mark==================setProperty======================
-(void)setProperty{
//    NSLog(@"reserveId:%@,levelLimit:%@,orderInfo:%@",_reserveId,_levelLimit,_orderInfo);
    
    if (_orderInfo[@"storeId"]) {
        _storeId=_orderInfo[@"storeId"];
    }
    if (_orderInfo[@"shopKeeper"]) {
        _shopKeeper=_orderInfo[@"shopKeeper"];
    }

    
    
    self.view.backgroundColor = ThemeBackgroundColor;
    self.navigationItem.title = kOrderLocalizeString(@"BKOrderChooseDeliveryDate");
    _ODCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    /*
     * 分享按钮
     */
    UIImage *image = [[UIImage imageNamed:@"BKGDShare"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(action_share:)];
    
    _matchNum_Index = -1;
    _marr_deliveryDate = [NSMutableArray array];
    _mdic_deliveryDate = [[NSMutableDictionary alloc]init];
    
    _send_Obj = [[BKODSendObject alloc] init];
    
    _formatter_date = [[NSDateFormatter alloc] init];
    _formatter_date.dateFormat = @"yyyy-MM-dd";
    
    _mini_mumDate = [_ODCalendar od_firstDayOfMonth:[NSDate date]];
    _maxi_mumDate = [_ODCalendar od_lastDayOfMonth:[NSDate date]];
    
}

#pragma mark==================createUI======================
-(void)createUI{

    _tabV_calendar = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tabV_calendar.backgroundColor = [UIColor clearColor];
    _tabV_calendar.showsVerticalScrollIndicator = NO;
    _tabV_calendar.delegate = self;
    _tabV_calendar.dataSource = self;
    [self.view addSubview:_tabV_calendar];
    
    /*
     * 加入购物车与立即付款
     */
    _view_ODBfooter = [[BK_OD_Footer_View alloc] init];
    _view_ODBfooter.delegate = self;
    [self.view addSubview:_view_ODBfooter];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dealWithKeyboard:)];
    tap.delegate = self;
    [_tabV_calendar addGestureRecognizer:tap];
    
    [self makeConstraints];
}

- (void)makeConstraints{
    [_view_ODBfooter mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.left.bottom.mas_equalTo(self.view);
        make.height.mas_equalTo(48);
    }];
    [_tabV_calendar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(64, 0, 48, 0));
    }];
}

#pragma mark============日历创建============
- (BKODCalendarView *)create_BK_CalendarView{
    
    
    BKODCalendarView *calendarView = [[BKODCalendarView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame) * 0.51)];
    calendarView.delegate = self;
    
    /*
     * 货权日历中显示的价格均为当日均价
     */
    BK_OD_Prompt_Msg *msg = [[BK_OD_Prompt_Msg alloc] init];
    [calendarView addSubview:msg];
    [msg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.left.mas_equalTo(calendarView);
        make.bottom.mas_equalTo(calendarView).offset(-3);
        make.height.mas_equalTo(17);
    }];
    
    /*
     * 左边翻页按钮
     */
    _btn_lastMonth = [[UIButton alloc] init];
    [_btn_lastMonth setImage:[UIImage imageNamed:@"BKOrderDDLeft"] forState:UIControlStateNormal];
    [_btn_lastMonth addTarget:self action:@selector(lastMonthAction:) forControlEvents:UIControlEventTouchUpInside];
    _btn_lastMonth.hidden = YES;
    [calendarView addSubview:_btn_lastMonth];
    [_btn_lastMonth mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(calendarView.calendarHeaderView);
        make.right.mas_equalTo(calendarView.mas_centerX).offset(-45);
        make.height.mas_equalTo(calendarView.calendarHeaderView);
        make.width.mas_equalTo(50);
    }];
    
    /*
     * 右边翻页按钮
     */
    _btn_nextMonth = [[UIButton alloc] init];
    [_btn_nextMonth setImage:[UIImage imageNamed:@"BKOrderDDRight"] forState:UIControlStateNormal];
    [_btn_nextMonth addTarget:self action:@selector(nextMonthAction:) forControlEvents:UIControlEventTouchUpInside];
    /*
     * 如果当前月份是最大的月份 或者 最大月份和最小月份是 同一个月份   -》隐藏
     */
    _btn_nextMonth.hidden = ([BK_Calendar_Tool isCurrentMonth:_maxi_mumDate] || [BK_Calendar_Tool IsInTheSameMonth:_maxi_mumDate :_mini_mumDate]) ? YES : NO;
    [calendarView addSubview:_btn_nextMonth];
    [_btn_nextMonth mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(calendarView.calendarHeaderView);
        make.left.mas_equalTo(calendarView.mas_centerX).offset(45);
        make.height.mas_equalTo(calendarView.calendarHeaderView);
        make.width.mas_equalTo(50);
    }];
    
    return calendarView;
}

#pragma mark============Footer============
- (BK_OD_Footer_PromptMsg *)creatTableFooterView{//限购提示
    if (![self isLimit]) {
        return nil;
    }
    
    BK_OD_Footer_PromptMsg *footerView = [[BK_OD_Footer_PromptMsg alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 35)];
    footerView.delegate = self;
    footerView.message = _levelLimit[@"quotaMessage"];
    
    return footerView;
}


//是否限购
- (BOOL)isLimit{
    NSNumber *quotaFlag = _levelLimit[@"quotaFlag"];
    return [quotaFlag boolValue];
}
//限购的个数
- (NSInteger)limitBuyCount{
    NSNumber *canBuyAmount = _levelLimit[@"canBuyAmount"];
    return [canBuyAmount integerValue];
}

#pragma mark============键盘通知============
- (void)BK_add_KeyboardNotifications{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
#pragma mark============键盘将要出现============
- (void)keyboardWillShow:(NSNotification *)nottification{
    NSDictionary *userInfo = [nottification userInfo];
    CGRect keyboardRect = [[userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    [UIView animateWithDuration:1 animations:^{
        self.view.bounds = CGRectMake(0,CGRectGetHeight(keyboardRect) - 48, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame));
    }];
    _isKeyboardIsVisible = YES;
}
#pragma mark============键盘将要消失============
- (void)keyboardWillHide:(NSNotification *)nottification{
    [UIView animateWithDuration:1 animations:^{
        self.view.bounds = self.view.frame;
    }];
    _isKeyboardIsVisible = NO;
}
#pragma mark============构建Arr_Section============
- (void)BK_create_Arr_Section:(BKODDeliveryDate *)deliveryDate strongestMatchData:(BKODStrongestMatch *)data{
    if (_arr_section) {
        _arr_section = nil;
    }
    
    NSMutableArray *sectionArr = [NSMutableArray array];
    NSMutableArray *cellArr = [NSMutableArray array];

    if (!deliveryDate) {
        [_view_ODBfooter setCanSubmit:NO];
        return;
    }

    //选择出价
    CellModel *c0 = [[CellModel alloc] init];
    c0.className = NSStringFromClass([BK_OD_Price_Cell class]);
    c0.reuseIdentifier = @"c0";
    c0.height = [BK_OD_Price_Cell computeHeight:nil];
    c0.delegate = self;
    c0.userInfo = @{@"delivery" : deliveryDate, @"strongMatch" : data ? data : [NSNull null]};
    
    [cellArr addObject:c0];
    _send_Obj.price = data ? [data.price stringValue] : _send_Obj.price;
    
    //选择数量
    CellModel *c1 = [[CellModel alloc] init];
    c1.className = NSStringFromClass([BK_OD_Count_Cell class]);
    c1.reuseIdentifier = @"c1";
    c1.height = [BK_OD_Count_Cell computeHeight:nil];
    c1.delegate = self;
    NSString *count = data ? [data.count stringValue] : deliveryDate.amount;
    NSInteger limitCount = [self limitBuyCount];
    NSInteger minCountInteger = [count integerValue] < limitCount ? [count integerValue] :limitCount;
    NSString *minCount = [NSString stringWithFormat:@"%ld", (long)minCountInteger];
    c1.userInfo = @{@"deliveryDateModel" : deliveryDate, @"count" : minCount};
    _send_Obj.amount = @"1";
    [cellArr addObject:c1];
    _countIndex = [cellArr indexOfObject:c1];
    
    
    if ([deliveryDate.thbuyflag isEqualToString:@"1"]){
        //出价匹配
        CellModel *c2 = [[CellModel alloc] init];
        c2.className = NSStringFromClass([BK_OD_MatchNum_Cell class]);
        c2.reuseIdentifier = @"c2";
        c2.height = [BK_OD_MatchNum_Cell computeHeight:nil];
        c2.userInfo = @{@"numberOfMatches" : count, @"inventory" : deliveryDate.amount};
        [cellArr addObject:c2];
        _matchNum_Index = [cellArr indexOfObject:c2];
    }
    
    
    SectionModel *sm = [SectionModel sectionModelWithTitle:@"" cells:cellArr.copy];
    sm.headerhHeight = 10;
    sm.footerHeight = 0.1;
    
    [sectionArr addObject:sm];
    
    [_view_ODBfooter setCanSubmit:YES];
    _arr_section = sectionArr.copy;
    
    _tabV_calendar.tableFooterView = [self creatTableFooterView];
}

#pragma mark =================public methods
//获取节日
- (void)getSolarTerms:(void(^)())block{
    __weak typeof(self) weakSelf = self;
    EKEventStore *store = [[EKEventStore alloc] init];
    [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
        if(granted){
            NSDate *startDate = [_ODCalendar od_firstDayOfMonth:_mini_mumDate]; // 开始日期
            NSDate *endDate = [_ODCalendar od_lastDayOfMonth:_maxi_mumDate]; // 截止日期
            NSPredicate *fetchCalendarEvents = [store predicateForEventsWithStartDate:startDate endDate:endDate calendars:nil];
            
            NSArray<EKEvent *> *eventList = [store eventsMatchingPredicate:fetchCalendarEvents];
            NSArray<EKEvent *> *events = [eventList filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(EKEvent * _Nullable event, NSDictionary<NSString *,id> * _Nullable bindings) {
                return event.calendar.subscribed;
            }]];
            weakSelf.arr_events = events;
            dispatch_async(dispatch_get_main_queue(), ^{
                block();
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                block();
            });
        }
    }];
}

//获取某个日期全部事件
- (NSArray<EKEvent *> *)eventsForDate:(NSDate *)date{
    NSArray<EKEvent *> *filteredEvents = [self.arr_events filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(EKEvent * _Nullable evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
        return [evaluatedObject.occurrenceDate isEqualToDate:date];
    }]];
    return filteredEvents;
}

#pragma mark===============calendar 代理相关
- (NSString *)calendar:(BKODCalendarView *)calendar titleForDate:(NSDate *)date{//cell title
    if ([[_formatter_date stringFromDate:date] isEqualToString:[_formatter_date stringFromDate:[NSDate date]]]) {
        return @"今日";
    }
    //节日
    EKEvent *event = [self eventsForDate:date].firstObject;
    if (event) {
        return event.title;
    }
    return nil;
}
//subtitle
- (NSString *)calendar:(BKODCalendarView *)calendar subtitleForDate:(NSDate *)date{
    for (NSArray *dateArr in _marr_deliveryDate) {
        for (BKODDeliveryDate *dd in dateArr) {
            if ([date isEqual:[_formatter_date dateFromString:dd.date]]) {
                return dd.avgpriceStr;
            }
        }
    }
    return nil;
}
// cell should select
- (BOOL)calendar:(BKODCalendarView *)calendar shouldSelectDate:(NSDate *)date{
    for (NSArray *dateArr in _marr_deliveryDate) {
        for (BKODDeliveryDate *dd in dateArr) {
            if ([date isEqual:[_formatter_date dateFromString:dd.date]]) {
                return YES;
            }
        }
    }
    return NO;
}
// cell selected
- (void)calendar:(BKODCalendarView *)calendar didSelectDate:(NSDate *)date{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(300 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
        [self BK_Request_StrongestMatch:date];
    });
}
/*
 * 上一个月份
 */
#pragma mark----上一个月份
- (void)lastMonthAction:(UIButton *)sender{
    
    
    _str_Use_Month = [self Previous_Month];
//    _formatter_date = [[NSDateFormatter alloc] init];
//    _formatter_date.dateFormat = @"yyyy-MM-dd";
    NSDate *now_date = [_formatter_date dateFromString:[NSString stringWithFormat:@"%@-01",_str_Use_Month]];
    
//    [_view_calendar setCurrentPage:_mini_mumDate];
    
    [_view_calendar setCurrentPage:now_date];
    
    if ([_mdic_deliveryDate valueForKey:_str_Use_Month]) {
        NSMutableArray * marr=[[NSMutableArray alloc]init];
        marr=[_mdic_deliveryDate valueForKey:_str_Use_Month];
        BKODDeliveryDate *fristDate = marr.firstObject;
        NSDate *selectDate = [_formatter_date dateFromString:fristDate.date];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(300 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
            [_view_calendar selectDate:selectDate];
        });
    }
    
    
    if ([_str_Use_Month isEqualToString:_str_mini_Month]) {
        _btn_nextMonth.hidden = NO;
        _btn_lastMonth.hidden = YES;
    }else{
        _btn_nextMonth.hidden = YES;
        _btn_lastMonth.hidden = NO;
    }

}


/*
 * 下一个月份
 */
#pragma mark----下一个月份
- (void)nextMonthAction:(UIButton *)sender{
    
    _str_Use_Month = [self Next_Month];
    
    if ([_mdic_deliveryDate valueForKey:_str_Use_Month]) {
        /*
         * 请求过的数据   直接读取
         */
        NSDate *now_date = [_formatter_date dateFromString:[NSString stringWithFormat:@"%@-01",_str_Use_Month]];
        [_view_calendar setCurrentPage:now_date];
        
        NSMutableArray * marr=[[NSMutableArray alloc]init];
        marr=[_mdic_deliveryDate valueForKey:_str_Use_Month];
        BKODDeliveryDate *fristDate = marr.firstObject;
        
        NSDate *selectDate = [_formatter_date dateFromString:fristDate.date];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(300 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
            [_view_calendar selectDate:selectDate];
        });
        
    }else{
        
        /*
         * 重新请求
         */
        __weak typeof(self)weakSelf = self;
        NSString *reserveId = _reserveId;//库存id
        
        [BK_Calendar_Tool BK_ListCalendar:^(BOOL isSuccess, id obj, NSError *error) {
            
            if (isSuccess) {
                
                NSMutableArray *dateArr = [NSMutableArray array];
                for (NSDictionary *dateList in obj[@"data"][@"list"]) {
                    
                    BKODDeliveryDate *ddc = [BKODDeliveryDate mj_objectWithKeyValues:dateList];
                    [dateArr addObject:ddc];
                    
                }
                if (dateArr.count == 0) {
//                    return;
                    dateArr=nil;
                }
                [_marr_deliveryDate addObject:dateArr.copy];
                
                
                
                /*
                 * 将其加入字典
                 */
                NSString * key_month =obj[@"data"][@"month"];
                NSMutableArray * value_List = [NSMutableArray arrayWithArray:dateArr];
                [_mdic_deliveryDate setValue:value_List forKey:key_month];

                
                
                
                NSArray *dataSource = _marr_deliveryDate.firstObject;
                
                BKODDeliveryDate *ddc = dataSource.firstObject;
                NSDate *shouldSelectDate = [_formatter_date dateFromString:ddc.date];
                //当节气请求完成在开始加载日历（避免日历已经加载完成时节气还没请求到）
                [weakSelf getSolarTerms:^{
                    
                    if (!_view_calendar) {
                        
                        _view_calendar = [self create_BK_CalendarView];
                        _view_calendar.minimumDate = [_ODCalendar od_firstDayOfMonth:_mini_mumDate];
                        _view_calendar.maximumDate = [_ODCalendar od_lastDayOfMonth:_maxi_mumDate];
                        [_view_calendar reloadData];
                        _tabV_calendar.BKOrder_Header = _view_calendar;
                        
                        [_view_calendar setCurrentPage:shouldSelectDate];
                        [_view_calendar selectDate:shouldSelectDate];
                        
                    }else{
                        //                    [_view_calendar reloadData];
                        //                    [_view_calendar setCurrentPage:shouldSelectDate];
                        //                    [_view_calendar selectDate:shouldSelectDate];
                    }
                    
                    //给下级页面传参使用
                    _send_Obj.sendDate = ddc.date;
                    _send_Obj.thbuyflag = ddc.thbuyflag;
                    _send_Obj.price = ddc.avgprice;
                    
                    [weakSelf BK_Request_StrongestMatch:shouldSelectDate];
                    
                }];
                

                NSDate *now_date = [_formatter_date dateFromString:[NSString stringWithFormat:@"%@-01",_str_Use_Month]];
                [_view_calendar setCurrentPage:now_date];
                
                NSMutableArray * marr=[[NSMutableArray alloc]init];
                marr=[_mdic_deliveryDate valueForKey:_str_Use_Month];
                BKODDeliveryDate *fristDate = marr.firstObject;
                
                NSDate *selectDate = [_formatter_date dateFromString:fristDate.date];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(300 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
                    [_view_calendar selectDate:selectDate];
                });
                
                
            }
            
        } WithReserveId:reserveId andMonth:_str_Use_Month];
        

    }
    
    if ([_str_Use_Month isEqualToString:_str_max_Month]) {
        _btn_nextMonth.hidden = YES;
        _btn_lastMonth.hidden = NO;
    }else{
        _btn_nextMonth.hidden = NO;
        _btn_lastMonth.hidden = YES;
    }

}

#pragma mark table  代理相关
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _arr_section.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    SectionModel *sm = _arr_section[section];
    return sm.cells.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SectionModel *sm = _arr_section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    
    BK_OD_Cell *cell = [tableView dequeueReusableCellWithIdentifier:cm.reuseIdentifier];
    if (!cell){
        cell = [[NSClassFromString( cm.className) alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cm.reuseIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = cm.delegate;

    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    SectionModel *sm = _arr_section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    
    BK_Confirm_Order_Cell *cellzz = (BK_Confirm_Order_Cell *)cell;
    
    SEL fillData = @selector(fillData:);
    if ([cellzz respondsToSelector:fillData]) {
        #pragma clang diagnostic push
        #pragma clang diagnostic ignored"-Warc-performSelector-leaks"
        [cellzz performSelector:fillData withObject:cm.userInfo];
        #pragma clang diagnostic pop
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    SectionModel *sm = _arr_section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    return cm.height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    SectionModel *sm = _arr_section[section];
    return sm.headerhHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    SectionModel *sm = _arr_section[section];
    return sm.footerHeight;
}

#pragma cell delegate
- (void)ODSelectPriceCell:(BK_OD_Price_Cell *)cell didSelectPriceChanged:(NSString *)price{
    NSString *requestPrice = [@([price doubleValue] - _price_Difference) stringValue];
    
    [self BK_Request_BidWithPrice:requestPrice];
    _send_Obj.price = requestPrice;
}

- (void)ODSelectCountCell:(BK_OD_Count_Cell *)cell didSelectCountChanged:(NSString *)count{
    _send_Obj.amount = count;
}

#pragma mark  手势代理
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if (_isKeyboardIsVisible) {
        return YES;
    }
    return NO;
}

- (void)dealWithKeyboard:(UIGestureRecognizer *)recognizer{
    [_tabV_calendar endEditing:YES];
}
#pragma mark===============BKODBFooterViewDelegate
#pragma mark 限购详情
- (void)ODFooterPromptMsgPromptMsgShowDetails:(BK_OD_Footer_PromptMsg *)view{
    CGRect frame = CGRectMake(0, CGRectGetHeight([UIScreen mainScreen].bounds) - 360, CGRectGetWidth([UIScreen mainScreen].bounds), 360);
    BK_OD_LimitBuy_View *limitView = [[BK_OD_LimitBuy_View alloc] initWithFrame:frame];
    limitView.limitBuyData = _levelLimit;
    [limitView show];
}

#pragma mark 去购物车
- (void)ODBFooterViewGoShoppingCar{
    UIViewController *shoppingCarVC = [[Mediator sharedInstance] BKSC_shoppingCarViewController];
    shoppingCarVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:shoppingCarVC animated:YES];
}

#pragma mark 添加到购物车
- (void)ODBFooterViewAddShoppingCar{
    
    [BK_Calendar_Tool BK_AddShopping:^(BOOL isSuccess, id obj, NSError *error) {
        if (isSuccess) {
            [_view_ODBfooter updateShoppingCartAmount];
        }
    } WithIsOK:[self canAddShoppingOrPayment] andShoppingCarParamDic:[self ParamDic_shoppingCar] andLimitBuyCount:[self limitBuyCount]];

}
- (NSDictionary *)ParamDic_shoppingCar{
    NSString *goods_id        = _orderInfo[@"goods_id"];
    NSString *thnormaltype    = _orderInfo[@"thnormaltype"] ? _orderInfo[@"thnormaltype"] : @"";
    NSString *goods_pro_rel1  = _orderInfo[@"goods_pro_rel1"];
    NSString *goods_pro_rel2  = _orderInfo[@"goods_pro_rel2"];
    NSString *goods_pro_rel3  = _orderInfo[@"goods_pro_rel3"];
    NSString *goods_pro_rel4  = _orderInfo[@"goods_pro_rel4"];
    NSString *goods_pro_rel5  = _orderInfo[@"goods_pro_rel5"];
    NSString *goods_amount    = _send_Obj.amount; //...
    NSString *sendDate        = _send_Obj.sendDate;
    NSString *userPrice       = _send_Obj.price;
    NSString *thbuyflag       = _send_Obj.thbuyflag;
    NSString *integralGoodsId = @"";
    
    NSDictionary *paramDic;
    if (_shopKeeper&&_storeId) {
        paramDic= @{
                        @"goods_id"          : goods_id,
                        @"goods_amount"      : goods_amount,
                        @"goods_pro_rel1"    : goods_pro_rel1,
                        @"goods_pro_rel2"    : goods_pro_rel2,
                        @"goods_pro_rel3"    : goods_pro_rel3,
                        @"goods_pro_rel4"    : goods_pro_rel4,
                        @"goods_pro_rel5"    : goods_pro_rel5,
                        @"sendDate"          : sendDate,
                        @"userPrice"         : userPrice,
                        @"thbuyflag"         : thbuyflag,
                        @"thnormaltype"      : thnormaltype,
                        @"integralGoodsId"   : integralGoodsId,
                        
                        @"shopKeeper"      : _shopKeeper,
                        @"storeId"   : _storeId,
                        
                    };
    }else{
         paramDic= @{
                       @"goods_id"          : goods_id,
                       @"goods_amount"      : goods_amount,
                       @"goods_pro_rel1"    : goods_pro_rel1,
                       @"goods_pro_rel2"    : goods_pro_rel2,
                       @"goods_pro_rel3"    : goods_pro_rel3,
                       @"goods_pro_rel4"    : goods_pro_rel4,
                       @"goods_pro_rel5"    : goods_pro_rel5,
                       @"sendDate"          : sendDate,
                       @"userPrice"         : userPrice,
                       @"thbuyflag"         : thbuyflag,
                       @"thnormaltype"      : thnormaltype,
                       @"integralGoodsId"   : integralGoodsId
                   };
    }
    
   
    return paramDic;
}

#pragma mark 立即购买
- (void)ODBFooterViewPayment{
    if ([RequestManager reachabilityStatus] == RequestReachabilityStatusUnknown || [RequestManager reachabilityStatus] == RequestReachabilityStatusNotReachable) {
        kOrderPromptMsg(@"请检查您的网络");
        return;
    }
    if ([self canAddShoppingOrPayment] == NO){
        return;
    }
    NSDictionary *paramDic = [self ParamDic_Pay];
    
    NSInteger amount = [paramDic[@"amount"] integerValue];
    NSInteger limitBuyCount = [self limitBuyCount];
    if (amount > limitBuyCount) {
        NSString *promptMsg = [NSString stringWithFormat:@"最多购买%ld件",(long)limitBuyCount];
        kOrderPromptMsg(promptMsg);
        return;
    }
    
    UIViewController *orderVC = [[Mediator sharedInstance] BKOrder_orderViewControllerWithParameter:@{@"orderInfo" : @[paramDic]}];
    [self.navigationController pushViewController:orderVC animated:YES];
}

- (NSDictionary *)ParamDic_Pay{
    NSMutableDictionary *paramDic = [self ParamDic_shoppingCar].mutableCopy;
    [paramDic setObject:paramDic[@"goods_amount"] forKey:@"amount"];
    [paramDic removeObjectForKey:@"goods_amount"];
    [paramDic setObject:_reserveId forKey:@"goods_reserve_id"];
    return paramDic.copy;
}

/*
 * 是否可 加购物车 去购买
 */
- (BOOL)canAddShoppingOrPayment{
    if ([_send_Obj.thbuyflag isEqualToString:@"1"]) {
        CellModel *cm = _arr_section.lastObject.cells[_matchNum_Index];
        NSInteger numberOfMatches = [cm.userInfo[@"numberOfMatches"] integerValue];
        if (numberOfMatches == 0) {
            kOrderPromptMsg(@"出价匹配数为0");
            return NO;
        }
        if ([_send_Obj.amount integerValue] == 0) {
            kOrderPromptMsg(@"商品数量不能为0");
            return NO;
        }
    }
    return YES;
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma ====================================Action========================================
#pragma mark==================分享======================
- (void)action_share:(UIBarButtonItem *)sender{
    __weak typeof(self) weakSelf = self;
    [[ShareManager manager] showShareMenuInController:weakSelf sharePlatformSelectionBlock:^ShareObject *(SharePlatformType type) {
        
        NSArray *images = _orderInfo[@"goods_images"];
        
        ShareObject *obj = [[ShareObject alloc] init];
        obj.title = _orderInfo[@"goods_name"];
        obj.descr = _orderInfo[@"shareRemark"];
        obj.thumbImage = images.count ? images.firstObject : @"";
        
        NSDictionary *userInfo = [[Mediator sharedInstance] BKMyUserInfo];
        NSString *value = userInfo[@"BKMyUserInfoUserVistorIdKey"];
        value = value ? value : @"";
        
        NSString *shareUrl = [NSString stringWithFormat:@"%@%@?%@%@",@"invite/",value,@"goods_no=",_orderInfo[@"goods_id"]];
        
        obj.webpageUrl = kOrderWebURL(shareUrl);
        return obj;
        
    } callBack:nil];
}
#pragma ====================================API========================================
#pragma mark==================checkNet======================
-(void)check_NetWork{
    RequestReachabilityStatus status = [RequestManager reachabilityStatus];
    switch (status) {
        case RequestReachabilityStatusReachableViaWiFi:
        case RequestReachabilityStatusReachableViaWWAN: {
            /*
             * 查询日历可卖日期区间
             */
            [self BK_Request_ScopeOfMonth];
        }
            break;
        default: {
            [HUD dismiss];
            
            self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeNoNetwork];
            ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeNoNetwork handler:^(ExceptionViewAction *action) {
                [self.exceptionView dismiss];
                self.exceptionView = nil;
                [self check_NetWork];
            }];
            [self.exceptionView addAction:action];
            [self.exceptionView showInView:self.view];
        }
            break;
    }
}
#pragma mark==================查询日历可卖日期区间======================
- (void)BK_Request_ScopeOfMonth{
    __weak typeof(self)weakSelf = self;
    if (self.exceptionView) {
        [self.exceptionView dismiss];
        self.exceptionView = nil;
    }
    [BK_Calendar_Tool BK_Calendar_ThsalebetweenDays:^(BOOL isSuccess, id obj, NSError *error) {
        if (isSuccess) {
            NSDictionary *scopeDates = obj[@"data"];
            
            NSDate *fristDay = [_formatter_date dateFromString:scopeDates[@"fristthDay"]];
            NSDate *lastDay = [_formatter_date dateFromString:scopeDates[@"lastthDay"]];
            
            _str_mini_Month=[scopeDates[@"fristthDay"] substringToIndex:7];
            _str_max_Month =[scopeDates[@"lastthDay"] substringToIndex:7];
            
            _mini_mumDate = fristDay;
            _maxi_mumDate = lastDay;
            
            /*
             * 日历囤货信息
             */
            [weakSelf BK_Request_CalendarInfo];
        }
        if (!weakSelf.exceptionView && error) {
            ExceptionCodeType codeType;
            if (error.code == -1001){
                codeType = ExceptionCodeTypeRequestFailed;
            }else{
                codeType = ExceptionCodeTypeServerError;
            }
            weakSelf.exceptionView = [ExceptionView exceptionViewWithType:codeType];
            weakSelf.exceptionView.backgroundColor = self.view.backgroundColor;
            ExceptionViewAction *action = [ExceptionViewAction actionWithType:codeType handler:^(ExceptionViewAction *action) {
                [weakSelf BK_Request_ScopeOfMonth];
            }];
            [weakSelf.exceptionView addAction:action];
            [weakSelf.exceptionView showInView:weakSelf.view];
        }

    } WithReserveId:_reserveId];
}

#pragma mark==================日历囤货信息======================
- (void)BK_Request_CalendarInfo{
    __weak typeof(self)weakSelf = self;
    NSString *reserveId = _reserveId;//库存id
    NSString *month = [[_formatter_date stringFromDate:_mini_mumDate] substringToIndex:7];//2017-02
    
    //如果数据数组已有值 请求月份为下一个月
    if (_marr_deliveryDate.count){
        BKODDeliveryDate *ddc = _marr_deliveryDate.lastObject.firstObject;
        month = [BK_Calendar_Tool BK_nextMonth:[_formatter_date dateFromString:ddc.date]];
    }
    _str_Use_Month = month;
    [BK_Calendar_Tool BK_ListCalendar:^(BOOL isSuccess, id obj, NSError *error) {
        if (isSuccess) {
            NSMutableArray *dateArr = [NSMutableArray array];
            for (NSDictionary *dateList in obj[@"data"][@"list"]) {
                BKODDeliveryDate *ddc = [BKODDeliveryDate mj_objectWithKeyValues:dateList];
                [dateArr addObject:ddc];
            }
            if (dateArr.count == 0) {
                //                    return;
                dateArr=nil;
            }
            [_marr_deliveryDate addObject:dateArr.copy];
            
            
            /*
             * 将其加入字典
             */
            NSString * key_month =obj[@"data"][@"month"];
            NSMutableArray * value_List = [NSMutableArray arrayWithArray:dateArr];
            [_mdic_deliveryDate setValue:value_List forKey:key_month];
  
            
            NSArray *dataSource = _marr_deliveryDate.firstObject;
            
            BKODDeliveryDate *ddc = dataSource.firstObject;
            NSDate *shouldSelectDate = [_formatter_date dateFromString:ddc.date];
            //当节气请求完成在开始加载日历（避免日历已经加载完成时节气还没请求到）
            [weakSelf getSolarTerms:^{
                if (!_view_calendar) {
                    _view_calendar = [self create_BK_CalendarView];
                    _view_calendar.minimumDate = [_ODCalendar od_firstDayOfMonth:_mini_mumDate];
                    _view_calendar.maximumDate = [_ODCalendar od_lastDayOfMonth:_maxi_mumDate];
                    [_view_calendar reloadData];
                    _tabV_calendar.BKOrder_Header = _view_calendar;
                    
                    [_view_calendar setCurrentPage:shouldSelectDate];
                    [_view_calendar selectDate:shouldSelectDate];
                }
                //给下级页面传参使用
                _send_Obj.sendDate = ddc.date;
                _send_Obj.thbuyflag = ddc.thbuyflag;
                _send_Obj.price = ddc.avgprice;
                
                [weakSelf BK_Request_StrongestMatch:shouldSelectDate];

            }];

        }
    } WithReserveId:reserveId andMonth:month];
    
}


#pragma mark==================请求当前选择日期的最强匹配价======================
- (void)BK_Request_StrongestMatch:(NSDate *)selectDate{
    
    __weak typeof(self) weakSelf = self;
    
    BKODDeliveryDate *deliveryDate;
    for (NSArray <BKODDeliveryDate *> *dateArr in _marr_deliveryDate){
        for (BKODDeliveryDate *DDDate in dateArr){
            NSDate *currentDate = [_formatter_date dateFromString:DDDate.date];
            if ([selectDate isEqual:currentDate]){
                deliveryDate = DDDate;
                _send_Obj.sendDate = DDDate.date;
                _send_Obj.thbuyflag = DDDate.thbuyflag;
                _send_Obj.price = DDDate.avgprice;
            }
        }
    }
    
    if ([deliveryDate.thbuyflag isEqualToString:@"0"]){//1:出价预购，0：普通预购， 2：固定出价",
        
        [self BK_create_Arr_Section:deliveryDate strongestMatchData:nil];
        
        if (_tabV_calendar.numberOfSections) {
            [_tabV_calendar reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
        }else{
            [_tabV_calendar reloadData];
        }
        kOrderDismiss;
        return;
    }
    
    NSString *reserveId = _reserveId;
    NSDictionary *paramDic = @{@"reserveId" : reserveId, @"date" : [_formatter_date stringFromDate:selectDate]};
    
    if (weakSelf.exceptionView) {
        [weakSelf.exceptionView dismiss];
        weakSelf.exceptionView = nil;
    }
    
    [BK_Calendar_Tool BK_Strongbid:^(BOOL isSuccess, id obj, NSError *error) {
        if (isSuccess) {
            NSDictionary *strongestMatchData = obj[@"data"];
            BKODStrongestMatch *strongMatch = [BKODStrongestMatch mj_objectWithKeyValues:strongestMatchData];
            _price_Difference = [strongMatch.price_v2 doubleValue] - [strongMatch.price doubleValue];
            [weakSelf BK_create_Arr_Section:deliveryDate strongestMatchData:strongMatch];
            
            
            if ([_tabV_calendar numberOfSections]){
                [_tabV_calendar reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
            }else{
                [_tabV_calendar reloadData];
            }
        }else{
            if (!weakSelf.exceptionView && error) {
                
                ExceptionCodeType codeType;
                if (error.code == -1001){
                    codeType = ExceptionCodeTypeRequestFailed;
                }
                else{
                    codeType = ExceptionCodeTypeServerError;
                }
                
                weakSelf.exceptionView = [ExceptionView exceptionViewWithType:codeType];
                weakSelf.exceptionView.backgroundColor = self.view.backgroundColor;
                ExceptionViewAction *action = [ExceptionViewAction actionWithType:codeType handler:^(ExceptionViewAction *action) {
                    [weakSelf BK_Request_StrongestMatch:selectDate];
                }];
                [weakSelf.exceptionView addAction:action];
                [weakSelf.exceptionView showInView:weakSelf.view];
            }
        }
    } WithParamDic:paramDic];
}


#pragma mark==================查询sku根据日期出价的匹配囤货数量======================
- (void)BK_Request_BidWithPrice:(NSString *)price{
    kOrderLoading;
    NSString *reserveId = _reserveId;
    NSString *date = [_formatter_date stringFromDate:_view_calendar.selectedDate];
    NSNumber *priceN = @([price doubleValue]);
    
    NSDictionary *paramDic = @{
                               @"reserveId" : reserveId,
                               @"date"      : date,
                               @"price"     : priceN
                               };
    
    [BK_Calendar_Tool BK_Bid:^(BOOL isSuccess, id obj, NSError *error) {
        if (isSuccess) {
            NSString *count = [obj[@"data"][@"count"] stringValue];
            
            SectionModel *sm = _arr_section.firstObject;
            
            //匹配个数
            CellModel *ncm = sm.cells[_matchNum_Index];
            NSIndexPath *ncmIndex = [NSIndexPath indexPathForRow:_matchNum_Index inSection:0];
            NSDictionary *userInfo = ncm.userInfo;
            NSMutableDictionary *mutableUserInfo = userInfo.mutableCopy;
            [mutableUserInfo setValue:count forKey:@"numberOfMatches"];
            userInfo = nil;
            ncm.userInfo = mutableUserInfo.copy;
            
            //选择数量
            CellModel *ccm = sm.cells[_countIndex];
            NSIndexPath *ccmIndex = [NSIndexPath indexPathForRow:_countIndex inSection:0];
            NSMutableDictionary *mutableInfo = [ccm.userInfo mutableCopy];
            NSInteger limitBuyCount = [self limitBuyCount];
            limitBuyCount = [count integerValue] < limitBuyCount ? [count integerValue] : limitBuyCount;
            NSString *minCount = [NSString stringWithFormat:@"%ld", (long)limitBuyCount];
            /*
             * 最少要选择1件商品
             */
            if ([minCount isEqualToString:@"0"]) {
                minCount=@"1";
            }
            [mutableInfo setObject:minCount forKey:@"count"];
            ccm.userInfo = mutableInfo.copy;
            
            [_tabV_calendar reloadRowsAtIndexPaths:@[ncmIndex, ccmIndex] withRowAnimation:UITableViewRowAnimationNone];
            [_view_ODBfooter setCanSubmit:YES];
        }
    } WithParamDic:paramDic andMatchNum:_matchNum_Index];
    
}


/*
 * 返回 yyyy-MM 格式
 */
-(NSString * )Previous_Month{
    
    NSString * year = [_str_Use_Month substringToIndex:4];
    NSString * month =[_str_Use_Month substringFromIndex:_str_Use_Month.length - 2 ];

    if ([month integerValue]==0) {
        month =[_str_Use_Month substringFromIndex:_str_Use_Month.length - 1 ];
    }
    
    if ([month integerValue]>9) {
        if ([month integerValue]==10) {
            month=@"09";
        }else{
            month=[NSString stringWithFormat:@"%ld",[month integerValue]-1];
        }
        
    }else{
        if ([month integerValue]==1) {
            year=[NSString stringWithFormat:@"%ld",[year integerValue]-1];
            month=@"12";
        }else{
           month=[NSString stringWithFormat:@"0%ld",[month integerValue]-1];
        }
    }
    
    return [NSString stringWithFormat:@"%@-%@",year,month];
   
}
/*
 * 返回 yyyy-MM 格式
 */
-(NSString * )Next_Month{
    
    NSString * year = [_str_Use_Month substringToIndex:4];
    NSString * month =[_str_Use_Month substringFromIndex:_str_Use_Month.length - 2 ];
    
    if ([month integerValue]==0) {
        month =[_str_Use_Month substringFromIndex:_str_Use_Month.length - 1 ];
    }
    
    if ([month integerValue]>8) {
        if ([month integerValue]==12) {
            month=@"01";
            year=[NSString stringWithFormat:@"%ld",[year integerValue]+1];
        }else{
            month=[NSString stringWithFormat:@"%ld",[month integerValue]+1];
        }
        
    }else{
        month=[NSString stringWithFormat:@"0%ld",[month integerValue]+1];
    }
    
    return [NSString stringWithFormat:@"%@-%@",year,month];
    
}

@end




























